!<template>
  <div>
    <div style="text-align: left;margin:5px 0;">
      <div class="page-header">用户管理</div>
      <a-button type="primary" @click="()=>{{addVisible = true}}">
        <template #icon>
          <plus-circle-outlined />
        </template>
        添加用户
      </a-button>
    </div>
    <a-table
      :columns="columns"
      :data-source="userList"
      :pagination="pagenation"
      :locale="{emptyText:'暂无用户数据'}"
      :loading="tableLoading"
      @change="changePage"
    >
      <template #headerCell="{ column }">
        <template v-if="column.key === 'userId'">
          <span>用户ID</span>
        </template>
      </template>

      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'userId'">
          <span>{{ record.userId }}</span>
        </template>
        <template v-else-if="column.key === 'password'">
          <div>
            <span style="color:#8c8c8c">{{ record.password }}</span>
          </div>
        </template>
        <template v-else-if="column.key === 'role'">
          <div>
            <a-tag color="#68945c" v-if="record.role === '0'">管理员</a-tag>
            <a-tag color="#4994c4" v-else-if="record.role === '1'">工作人员</a-tag>
          </div>
        </template>
        <template v-else-if="column.key === 'action'">
          <div class="account-actions">
            <a-tooltip title="修改" :mouseEnterDelay="0" :mouseLeaveDelay="0">
              <a-button type="primary" shape="circle" @click="editUser(record.key)">
                <template #icon>
                  <form-outlined />
                </template>
              </a-button>
            </a-tooltip>

            <a-popconfirm
              title="确认是否删除该用户?"
              ok-text="是"
              okType="danger"
              cancel-text="取消"
              @confirm="delUser(record.key)"
            >
              <template #icon>
                <question-circle-outlined style="color: red" />
              </template>
              <a-button type="danger" shape="circle">
                <template #icon>
                  <delete-outlined />
                </template>
              </a-button>
            </a-popconfirm>
          </div>
        </template>
      </template>
    </a-table>
  </div>
  <div>
    <a-modal v-model:visible="editVisible">
      <template #title>
        <div style="display: flex;
    align-items: center;">
          <user-outlined />
          <span style="margin-left:5px;">用户信息修改</span>
        </div>
      </template>
      <template #footer>
        <!-- <a-button key="back" @click="handleCancel">Return</a-button> -->
        <a-button key="submit" type="primary" @click="submitEdit">提交</a-button>
      </template>
      <div class="edit-container">
        <div class="edit-item">
          <span class="edit-item-title">
            <span style="margin-left:5px;">用户ID：</span>
          </span>
          <span class="edit-item-content">{{edit.userId}}</span>
        </div>
        <div class="edit-item">
          <span class="edit-item-title">
            <span style="margin-left:5px;">用户名：</span>
          </span>
          <span class="edit-item-content">
            <a-input
              v-model:value="editUserName"
              :placeholder="edit.userName"
              :disabled="!editCheck"
            >
              <template #suffix>
                <a-tooltip title="修改用户名（可选）">
                  <info-circle-outlined style="color: rgba(0, 0, 0, 0.45)" />
                </a-tooltip>
              </template>
            </a-input>
          </span>
          <span style="margin-left:10px;">
            <a-checkbox v-model:checked="editCheck">修改用户名</a-checkbox>
          </span>
        </div>
        <div class="edit-item">
          <span class="edit-item-title">
            <span style="margin-left:5px;">密码：</span>
          </span>
          <span class="edit-item-content">
            <a-tooltip title="输入账号的新密码（自动加密）">
              <a-input-password v-model:value="editPassword" :placeholder="edit.password"></a-input-password>
            </a-tooltip>
          </span>
        </div>
        <div class="edit-item">
          <span class="edit-item-title">
            <span style="margin-left:5px;">
              账号类型：
              <a-tooltip
                v-if="edit.role==='0'&&edit.userId===10000"
                title="系统管理员不能对自身进行身份变更"
                :mouseEnterDelay="0"
                :mouseLeaveDelay="0"
              >
                <info-circle-outlined style="color: rgba(0, 0, 0, 0.45);font-size: 14px;" />
              </a-tooltip>
            </span>
          </span>
          <span class="edit-item-content">
            <a-select
              ref="select"
              v-model:value="editRole"
              :disabled="edit.role==='0'&&edit.userId===10000"
              :placeholder="edit.role"
              style="width: 100px"
            >
              <a-select-option value="0">管理员</a-select-option>
              <a-select-option value="1">工作人员</a-select-option>
            </a-select>
          </span>
        </div>
        <div class="edit-item">
          <span class="edit-item-title">
            <span style="margin-left:5px;">
              账号权限：
              <a-tooltip
                v-if="edit.role==='0'"
                title="系统管理员不参与权限分配，默认开启所有权限"
                :mouseEnterDelay="0"
                :mouseLeaveDelay="0"
              >
                <info-circle-outlined style="color: rgba(0, 0, 0, 0.45);font-size: 14px;" />
              </a-tooltip>
            </span>
          </span>
          <span class="edit-item-content" style="width:70%;">
            <a-tag v-if="edit.role==='0'">全部权限</a-tag>
            <span v-else-if="edit.role!=='0'">
              <a-checkbox-group
                v-model:value="permissionValue"
                name="permissionGroup"
                :options="options"
              />
            </span>
          </span>
        </div>
      </div>
    </a-modal>
    <a-modal v-model:visible="addVisible">
      <template #title>
        <div style="display: flex;
    align-items: center;">
          <user-add-outlined />
          <span style="margin-left:5px;">用户信息添加</span>
        </div>
      </template>
      <template #footer>
        <!-- <a-button key="back" @click="handleCancel">Return</a-button> -->
        <a-button key="submit" type="primary" @click="submitAdd">添加</a-button>
      </template>
      <div class="edit-container">
        <div class="edit-item">
          <span class="edit-item-title">
            <span style="margin-left:5px;">用户名：</span>
          </span>
          <span class="edit-item-content">
            <a-input v-model:value="addInfo.addName" placeholder="用户昵称（可选）"></a-input>
            <!-- <span><a-button type="text" shape="circle"><reload-outlined /></a-button></span> -->
          </span>
        </div>
        <div class="edit-item">
          <span class="edit-item-title">
            <span style="margin-left:5px;">密码：</span>
          </span>
          <span class="edit-item-content">
            <a-tooltip title="账号的新密码">
              <a-input-password
                v-model:value="addInfo.addPwd"
                placeholder="账号密码"
                :disabled="addInfo.defPwd"
              ></a-input-password>
            </a-tooltip>
          </span>
          <span style="margin-left:10px;">
            <a-checkbox v-model:checked="addInfo.defPwd">使用默认密码</a-checkbox>
            <a-tooltip title="系统自动设置密码为123456">
              <info-circle-outlined style="color: rgba(0, 0, 0, 0.45)" />
            </a-tooltip>
          </span>
        </div>
        <div class="edit-item">
          <span class="edit-item-title">
            <span style="margin-left:5px;">账号类型：</span>
          </span>
          <span class="edit-item-content">
            <a-select
              ref="select"
              v-model:value="addInfo.addType"
              placeholder="创建账号的类型"
              style="width: 100px"
            >
              <a-select-option value="0">管理员</a-select-option>
              <a-select-option value="1">工作人员</a-select-option>
            </a-select>
          </span>
        </div>
        <div class="edit-item">
          <span class="edit-item-title">
            <span style="margin-left:5px;">账号权限：</span>
          </span>
          <span class="edit-item-content" style="width:70%;">
            <span>
              <a-checkbox-group
                v-if="addInfo.addType!=='0'"
                v-model:value="addInfo.addPermission"
                name="permissionGroup"
                :disabled="addInfo.addType==='0'"
                :options="options"
              />
              <a-tag v-else-if="addInfo.addType==='0'">全部权限</a-tag>
            </span>
          </span>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { ref } from "vue";
import { message } from "ant-design-vue";
import { sha256 } from "js-sha256";
import {
  DeleteOutlined,
  FormOutlined,
  QuestionCircleOutlined,
  UserOutlined,
  IdcardOutlined,
  LockOutlined,
  InfoCircleOutlined
} from "@ant-design/icons-vue";
import { selectList, deleteUser, addUser, editUser } from "@/api/user";
let pagenation = {
  pageSize: 5,
  total: 0
};
const options = [
  { label: "用户管理", value: "account" },
  { label: "商品管理", value: "commodity" },
  { label: "门店管理", value: "store" },
  { label: "采购管理", value: "purchase" },
  { label: "入库管理", value: "warehouse" },
  { label: "销售报表", value: "sell" },
  { label: "系统管理", value: "system" },
  { label: "供应商管理", value: "supplier" }
];
const columns = [
  {
    name: "userId",
    dataIndex: "userId",
    width: 180,
    key: "userId"
  },
  {
    title: "用户名",
    dataIndex: "userName",
    width: 180,
    key: "userName"
  },
  {
    title: "密码(已加密显示)",
    width: 180,
    dataIndex: "password",
    key: "password"
  },
  {
    title: "账号类型",
    key: "role",
    dataIndex: "role"
  },
  {
    title: "操作",
    key: "action"
  }
];
export default {
  name: "account",
  components: {
    DeleteOutlined,
    FormOutlined,
    QuestionCircleOutlined,
    UserOutlined,
    IdcardOutlined,
    LockOutlined,
    InfoCircleOutlined
  },
  setup() {
    return {
      columns,
      pagenation,
      editVisible: ref(false),
      addVisible: ref(false),
      tableLoading: ref(true),
      editPassword: ref(""),
      editUserName: ref(""),
      editCheck: ref(false),
      editRole: ref(null),
      permissionValue: ref([]),
      addInfo: ref({
        addName: "",
        addPwd: "",
        addType: "1",
        defPwd: true,
        addPermission: []
      }),
      options
    };
  },

  data() {
    return {
      edit: null,
      userList: []
    };
  },

  mounted() {
    this.tableLoading = true;
    this.getList(1, 6);
  },

  methods: {
    delUser(index) {
      index = index !== null && index !== undefined ? index : -1;
      let that = this;
      that.tableLoading = true;
      const res = deleteUser({
        userId: this.userList[index].userId
      });
      res
        .then(response => {
          this.tableLoading = true;
          //这里是请求成功后的操作
          console.log(response);
          if (response.code === 100) {
            message.success(response.msg);
            that.getList(1, 6);
          } else {
            message.warning(response.msg);
          }
          that.tableLoading = false;
          that.editVisible = false;
        })
        .catch(error => {
          that.tableLoading = false;
          that.editVisible = false;
          console.log(error);
        });
    },
    editUser(index = 0) {
      this.editVisible = true;
      this.edit = this.userList[index];
      this.editRole = this.edit.role;
      let p = this.edit.permission;
      p = p.replace("[", "");
      p = p.replace("]", "");
      p = p.replace(/\s*/g, "");
      this.permissionValue = p.trim().split(",");
    },
    submitAdd() {
      let that = this;
      const res = addUser({
        userName: this.addInfo.addName
          ? this.addInfo.addName
          : "user" + Date.now(),
        password: this.addInfo.defPwd
          ? sha256("123456")
          : sha256(this.addInfo.addPwd),
        role: this.addInfo.addType,
        roleName: this.addInfo.addType === "0" ? "管理员" : "工作人员",
        permission: this.addInfo.addPermission
      });
      res
        .then(response => {
          this.tableLoading = true;
          //这里是请求成功后的操作
          console.log(response);
          if (response.code === 100) {
            message.success(response.msg);
            that.getList(1, 6);
          } else {
            message.warning(response.msg);
          }
          that.tableLoading = false;
          that.addVisible = false;
        })
        .catch(error => {
          that.tableLoading = false;
          that.addVisible = false;
          console.log(error);
        });
    },
    submitEdit() {
      let that = this;
      const res = editUser({
        userId: this.edit.userId,
        userName: this.editCheck ? this.editUserName : this.edit.userName,
        password: this.editPassword === "" ? "" : sha256(this.editPassword),
        role: this.editRole,
        permission: this.permissionValue
      });
      res
        .then(response => {
          this.tableLoading = true;
          //这里是请求成功后的操作
          console.log(response);
          if (response.code === 100) {
            message.success(response.msg);
            that.getList(1, 6);
          } else {
            message.warning(response.msg);
          }
          that.tableLoading = false;
          that.editVisible = false;
        })
        .catch(error => {
          that.tableLoading = false;
          that.editVisible = false;
          console.log(error);
        });
    },
    async getList(p = 1, s = 6) {
      const res = selectList({
        pageNum: p,
        pageSize: s
      });

      let that = this;
      res
        .then(response => {
          //这里是请求成功后的操作
          console.log(response);
          if (response.code === 100) {
            that.userList = [];
            let i = 0;
            for (const key in response.data.list) {
              if (response.data.list.hasOwnProperty(key)) {
                const element = response.data.list[key];
                element.key = i;
                i += 1;
                that.userList.push(element);
                that.pagenation.total = response.data.total;
              }
            }
          }
          that.tableLoading = false;
        })
        .catch(error => {
          that.tableLoading = false;
          message.error(error.message);
          console.log(error);
        });
    },
    changePage(pagination) {}
  }
};
</script>

<style scoped>
.page-header {
  font-size: 22px;
  color: #616161;
  margin: 0.5rem 0;
}
.edit-container {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}
.edit-item-title {
  user-select: none;
  width: 110px;
  font-size: 16px;
}
.edit-item-content {
  margin-left: 1rem;
  color: rgb(126, 126, 126);
}
.edit-item {
  display: flex;
  justify-content: flex-start;
  align-items: flex-end;
}
.account-actions {
  display: flex;
  gap: 1rem;
}
</style>